package com.tyj.movie.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyj.movie.constant.OrderStatusEnum;
import com.tyj.movie.constant.RedisConstant;
import com.tyj.movie.entity.MovieTheatreOrder;
import com.tyj.movie.mapper.MovieTheatreOrderMapper;
import com.tyj.movie.service.MovieTheatreOrderService;
import com.tyj.movie.util.AlipayTemplate;
import com.tyj.movie.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tyj
 * @since 2021-06-28
 */
@Service
public class MovieTheatreOrderServiceImpl extends ServiceImpl<MovieTheatreOrderMapper, MovieTheatreOrder> implements MovieTheatreOrderService {

    @Autowired
    MovieTheatreOrderMapper movieTheatreOrderMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    AlipayTemplate alipayTemplate;

    @Override
    public void closeOrder(MovieTheatreOrder movieTheatreOrder) {
        //查看订单状态
        MovieTheatreOrder order = movieTheatreOrderMapper.selectOne(new QueryWrapper<MovieTheatreOrder>().eq("order_sn", movieTheatreOrder.getOrderSn()));

        //待付款状态
        if (order.getState() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //将待付款状态修改为取消状态
            movieTheatreOrderMapper.updateOrderState(movieTheatreOrder.getOrderSn(), OrderStatusEnum.CANCLED.getCode());
            //将座位释放
            String[] seats = movieTheatreOrder.getSeat().split(",");
            redisTemplate.opsForSet().remove(RedisConstant.MOVIE_THEATRE_SEAT+movieTheatreOrder.getMovieTheatreShowId(),seats);

            //用户恶意下单数据更新
            BoundHashOperations<String, Object, Object> boundHashOperations = redisTemplate.boundHashOps(RedisConstant.USER_ORDER_SPITE_TOKEN);
            String redisKey=order.getMovieTheatreShowId() + "-" + order.getUserId();

            Object o = boundHashOperations.get(redisKey);
            boundHashOperations.put(redisKey,Integer.valueOf(o.toString())-1+"");

            //当到0时删除该key
            Object o1 = boundHashOperations.get(redisKey);
            if (Integer.valueOf(o1.toString())==0){
                //删除key
                boundHashOperations.delete(redisKey);
            }
        }

    }


    /**
     * 支付成功后 修改订单状态
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        String orderSn = vo.getOut_trade_no();
        //查看当前用户的状态
        MovieTheatreOrder order = movieTheatreOrderMapper.selectOne(new QueryWrapper<MovieTheatreOrder>().eq("order_sn",orderSn));
        if (order.getState()==OrderStatusEnum.CREATE_NEW.getCode()){
            this.baseMapper.updateOrderStateAndTradeNo(orderSn,OrderStatusEnum.PAYED.getCode(),vo.getTrade_no());
            //用户恶意下单数据更新
            BoundHashOperations<String, Object, Object> boundHashOperations = redisTemplate.boundHashOps(RedisConstant.USER_ORDER_SPITE_TOKEN);
            String redisKey=order.getMovieTheatreShowId() + "-" + order.getUserId();

            Object o = boundHashOperations.get(redisKey);
            Integer integer = Integer.valueOf(o.toString());
            boundHashOperations.put(redisKey,integer-1+"");

            //当到0时删除该key
            Object o1 = boundHashOperations.get(redisKey);
            if (Integer.valueOf(o1.toString())<=0){
                //删除key
                boundHashOperations.delete(redisKey);
            }
        }
        return "success";
    }

    @Override
    public void refundOrder(MovieTheatreOrder movieTheatreOrder) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayTemplate.getGatewayUrl(), alipayTemplate.getApp_id(), alipayTemplate.getMerchant_private_key(), "json", "GBK", alipayTemplate.getAlipay_public_key(), "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        String str = "{" +
                "\"trade_no\":" + movieTheatreOrder.getTradeNo() + "," +
                "\"out_trade_no\":" + movieTheatreOrder.getOrderSn() + "," +
                "\"out_request_no\":\"HZ01RF001\"," +
                "\"refund_amount\":" + movieTheatreOrder.getPrice() +
                "}";
        request.setBizContent(str);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        //改变当前订单状态
        movieTheatreOrderMapper.updateOrderState(movieTheatreOrder.getOrderSn(), OrderStatusEnum.REFUND.getCode());
    }
}
